package graphs

import (
	"io"
	"os"
	"path/filepath"
	"power/core/dao/graphdao"
	"power/core/dao/table"
	"power/core/localwrap"
	"power/core/service/graph"
	"strconv"

	"github.com/RocksonZeta/wrap/utils/cutil"
	"github.com/RocksonZeta/wrap/utils/mathutil"
)

type GraphElementProtos struct{}

func (s GraphElementProtos) Query(param graphdao.GraphElementProtosQueryParam) ([]table.GraphElementProto, int64) {
	ds := localwrap.GetRedisedMysql()
	defer ds.Close()
	return graphdao.GraphElementProtos{RedisedMysql: ds}.Query(param)
}
func (s GraphElementProtos) Get(id int) graph.GraphElementProto {
	ds := localwrap.GetRedisedMysql()
	defer ds.Close()
	return graphdao.GraphElementProtos{RedisedMysql: ds}.Get_(id)
}
func (s GraphElementProtos) ListByClassId(classId int) []graph.GraphElementProto {
	ds := localwrap.GetRedisedMysql()
	defer ds.Close()
	return graphdao.GraphElementProtos{RedisedMysql: ds}.ListByClassId_(classId)
}
func (s GraphElementProtos) Add(param graphdao.GraphElementProtosAddParam) table.GraphElementProto {
	ds := localwrap.GetRedisedMysql()
	defer ds.Close()
	return graphdao.GraphElementProtos{RedisedMysql: ds}.Add(param)
}
func (s GraphElementProtos) Delete(id int) {
	ds := localwrap.GetRedisedMysql()
	defer ds.Close()
	graphdao.GraphElementProtos{RedisedMysql: ds}.Delete(id)
}
func (s GraphElementProtos) Update(param graphdao.GraphElementProtosUpdateParam) {
	ds := localwrap.GetRedisedMysql()
	defer ds.Close()
	graphdao.GraphElementProtos{RedisedMysql: ds}.Update(param)
}
func (s GraphElementProtos) UpdateProp(id int, props string) {
	ds := localwrap.GetRedisedMysql()
	defer ds.Close()
	graphdao.GraphElementProtos{RedisedMysql: ds}.UpdateProps(id, props)
}

type GraphElementProtoProps struct {
	Proto  graph.GraphElementProto
	Data   []table.GraphElementProtoField
	Market []table.GraphElementProtoField
}

func (s GraphElementProtos) GetWithProps(id int) GraphElementProtoProps {
	ds := localwrap.GetRedisedMysql()
	defer ds.Close()
	var r GraphElementProtoProps
	r.Proto = graphdao.GraphElementProtos{RedisedMysql: ds}.Get_(id)
	fs := graphdao.GraphElementProtoFields{RedisedMysql: ds}.ListByProtoId(id)
	var fsMap map[string][]table.GraphElementProtoField
	cutil.Group(fs, &fsMap, "Field")
	r.Data = fsMap["data"]
	r.Market = fsMap["market"]
	return r

}

type SaveFileResult struct {
}

func (s GraphElementProtos) SaveFile(f io.ReadSeeker, uid int, ext string) (string, error) {
	dir := filepath.Join(localwrap.Config.Upload.ProtoIconDir, strconv.Itoa(uid/2000+1), strconv.Itoa(uid))
	if _, err := os.Stat(dir); os.IsNotExist(err) {
		os.MkdirAll(dir, 0755)
	}
	abs := filepath.Join(dir, mathutil.RandomStr(10, false)+ext)
	dst, err := os.OpenFile(abs, os.O_CREATE|os.O_WRONLY, 0644)
	_, err = io.Copy(dst, f)
	return abs, err
}
